//
//  GonggaoViewController.m
//  YiqiMobile
//
//  Created by henry on 13-3-30.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "GonggaoViewController.h"
#import "Config.h"
#import "Utility.h"
#import "QuartzCore/QuartzCore.h"
#import "GonggaoViewCell.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "DefineAction.h"
#import "MBProgressHUD.h"
#import "RelypinglunView.h"
#import "EMAsyncImageView.h"

@interface GonggaoViewController ()
@end

@implementation GonggaoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor=UIColorFromRGB(0xfafafa);
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
     self.navigationItem.titleView=[Utility getTitleView:@"供稿"];
    self.voiceRecord=[[VoiceRecord alloc] init];
    self.voiceRecord.delegate=self;
    float height=416-50;
    if (iPhone5) {
        height+=88;
    }
    self.mytableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, height)];
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
    self.mytableView.backgroundColor=[UIColor clearColor];
    //self.mytableView.showsVerticalScrollIndicator=NO;
    self.mytableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.mytableView];
    self.arrayList=[NSMutableArray array];
    
    
    //语音或者文字供稿工具条背景
    UIImageView *toolsbg=[[UIImageView alloc] initWithFrame:CGRectMake(0, self.mytableView.frame.size.height, 320, 50)];
    toolsbg.userInteractionEnabled=YES;
    toolsbg.tag=90000;
    toolsbg.backgroundColor=[UIColor clearColor];
    toolsbg.image=[Utility imageNamed:@"yuyinbg3.png"];
    //左边按钮
    UIButton *leftButton=[Utility customButton:self action:@selector(switchButtonAction:) normalImage:@"keyboardButton.png" lightedImage:@"yuyinButton.png" frame:CGRectMake(2, 12, 27, 27) title:nil tag:90005];
    [toolsbg addSubview:leftButton];
    
    
    UILabel *yuyinLabel=[Utility detailTextLabel:CGRectMake(35, 16, 90, 17) andFontSize:12.0];
    yuyinLabel.text=@"长按语音说话";
    yuyinLabel.tag=90003;
    yuyinLabel.textColor=UIColorFromRGB(0x6e6e6e);
    [toolsbg addSubview:yuyinLabel];
    
    //语音按钮
    UIView *voiceRecordButton=[[UIView alloc] initWithFrame:CGRectMake(130, -25, 72, 72)];
    voiceRecordButton.tag=90001;
    voiceRecordButton.hidden=NO;
    voiceRecordButton.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"recordbutton_normal.png"]];
    [toolsbg addSubview:voiceRecordButton];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressBtn:)];
    [longPressGesture setDelegate:self];
    longPressGesture.minimumPressDuration=0.3;//默认0.5秒
    [voiceRecordButton addGestureRecognizer:longPressGesture];
    //文字输入框
    UIImageView *dialogbg=[[UIImageView alloc] initWithFrame:CGRectMake(40, 6, 256, 36)];
    dialogbg.image=[Utility imageNamed:@"daillogbg.png"];
    dialogbg.tag=90002;
    dialogbg.userInteractionEnabled=YES;
    dialogbg.hidden=YES;
    [toolsbg addSubview:dialogbg];
    self.dailogField=[[UITextField alloc] initWithFrame:CGRectMake(5, 0, 246, 36)];
    self.dailogField.backgroundColor=[UIColor clearColor];
   
    self.dailogField.font=[UIFont fontWithName:FONT_FAMILY size:15.0];
    self.dailogField.textColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
    self.dailogField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    self.dailogField.delegate=self;
    self.dailogField.layer.borderWidth=0;
    self.dailogField.returnKeyType=UIReturnKeyDone;
    [dialogbg addSubview:self.dailogField];
    //表情图片按钮
    /*UIImageView *faceIamge=[[UIImageView alloc] initWithFrame:CGRectMake(251, 11, 29, 29)];
    faceIamge.hidden=YES;
    faceIamge.image=[Utility imageNamed:@"gonggao_face.png"];
    [imageButtom addSubview:faceIamge];
    //分享按钮
    UIButton  *fenxiangButton=[Utility customButton:self action:@selector(fenxiangAction:) normalImage:@"fenxiangbottum.png" lightedImage:@"fenxiangbottum.png" frame:CGRectMake(285, 11, 29, 29) title:nil tag:22];
    [imageButtom addSubview:fenxiangButton];*/
    [self.view addSubview:toolsbg];
    [self initkeyboard];
    
    [self initFootLoadingMore];
     self.currpage=1;
     self.isEndData=YES;
    
	// Do any additional setup after loading the view.
}

-(void) loadPinglunFromServerBypageFirst{
    [self loadPinglunFromServer:1];
}

-(void) loadPinglunFromServer:(int) prePageId{
    if (prePageId==1) {
        [self.arrayList removeAllObjects];
    }
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    [param setObject:[self.gonggaoDict objectForKey:@"str1"] forKey:@"id"];
    [param setObject:@"1" forKey:@"type"];
    [param setObject:@(prePageId) forKey:@"jr.curPageNum"];
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],GGPINGLUNANDREPLY];
    
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
     [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    self.mytableView.tableFooterView.hidden=YES;
    self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            if ([[result  objectForKey:@"method"] isEqualToString:GGPINGLUNANDREPLY]) {//评论和回复列表
                NSArray *data=[result objectForKey:@"list"];
                if (data&&(NSNull*)data!=[NSNull null]&&data.count>0) {
                    [self.arrayList addObjectsFromArray:data];
                    self.isEndData=NO;
                    self.currpage+=1;
                    [self.mytableView  reloadData];
                }else{
                     self.isEndData=YES;
                }
            }else if ([[result objectForKey:@"method"] isEqualToString:ADDPINGLUN]) {//发表供稿评论
                self.dailogField.text=@"";
                [self loadPinglunFromServer:1];
            }
            
       }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
       }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    self.mytableView.tableFooterView.hidden=YES;
    self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:NO];
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    UIView *view=[self.view  viewWithTag:FOOTVIEWTAG];
    if (!self.isEndData&&self.arrayList.count>0&&scrollView.contentOffset.y+self.mytableView.frame.size.height-view.frame.size.height>=self.mytableView.contentSize.height) {
        self.mytableView.contentInset=UIEdgeInsetsMake(0, 0, view.frame.size.height, 0);
        self.mytableView.tableFooterView.hidden=NO;
     
            [self loadPinglunFromServer:self.currpage];
        
    }
}

-(void) initkeyboard{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}

//表视图委托
#pragma mark - Tableview datasource & delegates
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    if (section==0) {
        UIView *view=[[UIView alloc] initWithFrame:CGRectZero];
        view.backgroundColor=UIColorFromRGB(0xfafafa);
       //头像
        EMAsyncImageView *logo=[[EMAsyncImageView alloc] initWithFrame:CGRectMake(12.5, 12.5, 40, 40)];
         logo.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=3",[Utility  getServerUrl],DOWNFILEACTION,[self.gonggaoDict objectForKey:@"str4"]];
        [logo.layer setMasksToBounds:YES];
        [logo.layer setCornerRadius:20.0f];
        [view addSubview:logo];
        //昵称
        UILabel *nickName=[Utility detailTextLabel:CGRectMake(64, 15, 245, 20) andFontSize:15.0f];
        nickName.textColor=UIColorFromRGB(0x666666);
        nickName.numberOfLines=1;
        nickName.text=[self.gonggaoDict objectForKey:@"str3"];
        [view addSubview:nickName];
        
        //时间、越读数
        UILabel *comment=[Utility detailTextLabel:CGRectMake(64, 35, 245, 20) andFontSize:8.0f];
        comment.textColor=UIColorFromRGB(0x666666);
        comment.numberOfLines=1;
        NSString *detal=[Utility datefromSeconds:[self.gonggaoDict objectForKey:@"dat1"] andDateFormat:@"yyyy-MM-dd"];
        comment.text=[NSString stringWithFormat:@"%@ %@供稿  阅读数：%@",detal,[self.gonggaoDict objectForKey:@"str3"],[self.gonggaoDict objectForKey:@"count4"]];
        [view addSubview:comment];
        float origin_y=comment.frame.origin.y+comment.frame.size.height;
        float height=0.0f;
        switch ([[self.gonggaoDict objectForKey:@"count2"] integerValue]) {
            case 1:{//文本
               
                NSString *gonggaoContent=[self.gonggaoDict objectForKey:@"str5"];
                CGSize size=[Utility getStringSize:gonggaoContent font:font withMaxSize:CGSizeMake(250, 100)];
                UILabel *labelContent=[Utility detailTextLabel:CGRectMake(64, origin_y, 256, size.height) andFontSize:15.0f];
                labelContent.textColor=UIColorFromRGB(0x000000);
                labelContent.text=gonggaoContent;
                labelContent.numberOfLines=(size.height/20)+1;
                [view addSubview:labelContent];
                view.frame=CGRectMake(0, 0, 320, size.height+100);
                height=size.height;
                break;
            }
            case 2:{//图片
                EMAsyncImageView  *eMAsyncImageView=[[EMAsyncImageView alloc] initWithFrame:CGRectMake(64, origin_y, 100, 100)];
                eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[self.gonggaoDict objectForKey:@"str1"]];
                 eMAsyncImageView.imageId=[self.gonggaoDict objectForKey:@"str1"];
                [view addSubview:eMAsyncImageView];
                view.frame=CGRectMake(0, 0, 320, eMAsyncImageView.frame.size.height+100);
                height=eMAsyncImageView.frame.size.height;
                break;
            }
            case 3:{//语音
                UIButton *voiceButton=[UIButton buttonWithType:UIButtonTypeCustom];
                voiceButton.frame=CGRectMake(66, origin_y, 38, 38);
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
                 voiceButton.tag=section;
                [voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:voiceButton];
                 view.frame=CGRectMake(0, 0, 320, voiceButton.frame.size.height+100);
                height=voiceButton.frame.size.height;
                break;
            }
            case 4:{//视频
                
                break;
            }
        }

        //评论数
        UIImageView *imageView1=[[UIImageView alloc] initWithFrame:CGRectMake(75, 64+height+15, 17, 17)];
        imageView1.image=[Utility imageNamed:@"gonggao_pinglun.png"];
        [view addSubview:imageView1];
        UILabel *Label1=[Utility detailTextLabel:CGRectMake(95,height+64+15, 55, 14) andFontSize:12.0f];
        Label1.textColor=UIColorFromRGB(0x666666);
        Label1.numberOfLines=1;
        Label1.textAlignment=NSTextAlignmentLeft;
        Label1.text=[NSString stringWithFormat:@"%@",[self.gonggaoDict objectForKey:@"count3"]];
        [view addSubview:Label1];
        
        //收藏数
        UIImageView *imageView2=[[UIImageView alloc] initWithFrame:CGRectMake(145, height+64+15, 17, 17)];
        imageView2.image=[Utility imageNamed:@"gonggaoCell_shoucang.png"];
        [view addSubview:imageView2];
        UILabel *Label2=[Utility detailTextLabel:CGRectMake(168, height+64+16, 55, 14) andFontSize:12.0f];
        Label2.textColor=UIColorFromRGB(0x666666);
        Label2.numberOfLines=1;
        Label2.textAlignment=NSTextAlignmentLeft;
        Label2.text=[NSString stringWithFormat:@"%@",[self.gonggaoDict objectForKey:@"count1"]];
        [view addSubview:Label2];
        
        //分享数
        UIImageView *imageView3=[[UIImageView alloc] initWithFrame:CGRectMake(215, height+64+15, 17, 17)];
        imageView3.image=[Utility imageNamed:@"fenxianglist.png"];
        [view addSubview:imageView3];
        UILabel *Label3=[Utility detailTextLabel:CGRectMake(235, height+64+16, 55, 14) andFontSize:12.0f];
        Label3.textColor=UIColorFromRGB(0x666666);
        Label3.numberOfLines=1;
        Label3.textAlignment=NSTextAlignmentLeft;
        Label3.text=[NSString stringWithFormat:@"%@",[self.gonggaoDict objectForKey:@"count2"]];
        [view addSubview:Label3];
        return view;

    }else{
        NSDictionary *dict=[self.arrayList objectAtIndex:section-1];
        NSString *pinglunContent=[dict objectForKey:@"str5"];
        CGSize size=[Utility getStringSize:pinglunContent font:font withMaxSize:CGSizeMake(250, 100)];
        UIButton *view=[UIButton buttonWithType:UIButtonTypeCustom];
        view.tag=HEADERBUTTONTAG+section;
        [view addTarget:self action:@selector(onclickSectionAction:) forControlEvents:UIControlEventTouchUpInside];
        view.frame=CGRectMake(0, 0, 320, size.height+24);
        view.backgroundColor=UIColorFromRGB(0xfafafa);
        //分割线
        UIImageView *imageViewline=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 3)];
        imageViewline.image=[Utility imageNamed:@"gonggaoCell_line.png"];
        [view addSubview:imageViewline];
        
        //头像
        EMAsyncImageView *logo=[[EMAsyncImageView alloc] initWithFrame:CGRectMake(12.5, 12.5, 40, 40)];
        logo.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=3",[Utility  getServerUrl],DOWNFILEACTION,[self.gonggaoDict objectForKey:@"str4"]];
        [logo.layer setCornerRadius:20.0f];
        [view addSubview:logo];
     
        [logo.layer setMasksToBounds:YES];
        [logo.layer setCornerRadius:20.0f];
        [view addSubview:logo];
        //昵称
        UILabel *nickName=[Utility detailTextLabel:CGRectMake(60, 15, 245, 20) andFontSize:15.0f];
        nickName.textColor=UIColorFromRGB(0x000000);
        nickName.numberOfLines=1;
        nickName.text=[dict objectForKey:@"str2"];
        [view addSubview:nickName];
        
        //时间、评论
        UILabel *comment=[Utility detailTextLabel:CGRectMake(60, 35, 245, 15) andFontSize:8.0f];
        comment.textColor=UIColorFromRGB(0x666666);
        comment.numberOfLines=1;
        NSString *strdate=[Utility datefromSeconds:[dict objectForKey:@"dat1"] andDateFormat:@"yyyy-MM-dd"];
        comment.text=[NSString stringWithFormat:@"%@ %@  供稿  阅读数：%@",strdate,[dict objectForKey:@"str2"],@"156"];
        [view addSubview:comment];
         float origin_y=comment.frame.origin.y+comment.frame.size.height;
        float height=0.0f;
        switch ([[dict objectForKey:@"count2"] integerValue]) {
            case 1:{//文本
                
                NSString *gonggaoContent=[dict objectForKey:@"str5"];
                CGSize size=[Utility getStringSize:gonggaoContent font:font withMaxSize:CGSizeMake(250, 100)];
                UILabel *labelContent=[Utility detailTextLabel:CGRectMake(64, origin_y, 256, size.height) andFontSize:15.0f];
                labelContent.textColor=UIColorFromRGB(0x000000);
                labelContent.text=gonggaoContent;
                labelContent.numberOfLines=(size.height/20)+1;
                [view addSubview:labelContent];
                height=size.height;
                break;
            }
            case 2:{//图片
                EMAsyncImageView  *eMAsyncImageView=[[EMAsyncImageView alloc] initWithFrame:CGRectMake(64, origin_y, 100, 100)];
                eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[self.gonggaoDict objectForKey:@"str1"]];
                eMAsyncImageView.imageId=[dict objectForKey:@"str1"];
                [view addSubview:eMAsyncImageView];
                height=eMAsyncImageView.frame.size.height;
                break;
            }
            case 3:{//语音
                UIButton *voiceButton=[UIButton buttonWithType:UIButtonTypeCustom];
                voiceButton.frame=CGRectMake(66, origin_y, 38, 38);
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
                [voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
                voiceButton.tag=section;
                [voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
                [view addSubview:voiceButton];
                height=voiceButton.frame.size.height;
                break;
            }
            case 4:{//视频
                
                break;
            }
        }
        

        
        //时间
        UILabel *dateLabel=[Utility detailTextLabel:CGRectMake(150, origin_y+8, 150, 14) andFontSize:8.0f];
        dateLabel.textColor=UIColorFromRGB(0x666666);
        dateLabel.numberOfLines=1;
        dateLabel.textAlignment=NSTextAlignmentRight;
        dateLabel.text=[NSString stringWithFormat:@"%@   %@",[Utility datefromSeconds:[dict objectForKey:@"dat1"] andDateFormat:@"yyyy-MM-dd"],@"成员"];
        [view addSubview:dateLabel];
         view.frame=CGRectMake(0, 0, 320, size.height+10+55);
    return view;
    }
    
}

//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.arrayList count]+1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section==0){
        return 0;
   }
    NSArray *replyList=[[self.arrayList objectAtIndex:section-1] objectForKey:@"nrs"];
    return [replyList count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
   
    if (section==0) {
         float height=150.0f;
        switch ([[self.gonggaoDict objectForKey:@"count2"] integerValue]) {
            case 1:{//文本
                
                NSString *gonggaoContent=[self.gonggaoDict objectForKey:@"str5"];
                CGSize size=[Utility getStringSize:gonggaoContent font:font withMaxSize:CGSizeMake(250, 100)];
                height=size.height+100;
                break;
            }
            case 2:{//图片
                height=100+100;
                break;
            }
            case 3:{//语音
                 height=38+100;
                break;
            }
            case 4:{//视频
                
                break;
            }
        }
          return height;
    }else{
         NSDictionary *dict=[self.arrayList objectAtIndex:section-1];
        float height=0.0f;
        switch ([[dict objectForKey:@"count1"] integerValue]) {
            case 1:{//文本
                
                NSString *pinglunContent=[dict objectForKey:@"str5"];
                CGSize size=[Utility getStringSize:pinglunContent font:font withMaxSize:CGSizeMake(250, 100)];
                height=size.height;
                break;
            }
            case 2:{//图片
                height=100;
                break;
            }
            case 3:{//语音
                height=38;
                break;
            }
            case 4:{//视频
                
                break;
            }
        }
        return height+10+55;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GonggaoViewCell *cell;
    if (indexPath.section>0) {
         cell = [[GonggaoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"section1"];
        NSArray *replyList=[[self.arrayList objectAtIndex:indexPath.section-1] objectForKey:@"nrs"];
        NSDictionary *dict = [replyList objectAtIndex:indexPath.row];
        UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
        CGSize size=[Utility getStringSize:[dict objectForKey:@"str5"] font:font withMaxSize:CGSizeMake(250, 100)];
        float height=23.0f;
        if (indexPath.row==0) {
           [cell setFrame:CGRectMake(0, 0, 320, size.height+33)];
            UIImageView *sanjiao=[[UIImageView alloc] initWithFrame:CGRectMake(60, 0, 255, 41)];
            sanjiao.image=[Utility imageNamed:@"gonggaocell_bg.png"];
            [cell  insertSubview:sanjiao aboveSubview:cell.backGround];
             cell.backGround.frame=CGRectMake(64, 41, 249, cell
                                              .frame.size.height-41);
            cell.contentText.frame=CGRectMake(70, 23, 230,  size.height);
            height=23.0f;
           
        }else{
            static NSString *cellIdentity = @"gonggaoViewCell";
            cell = (GonggaoViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
            if (cell ==  nil) {
                cell = [[GonggaoViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
            }
            [cell setFrame:CGRectMake(0, 0, 320,  size.height+15)];
            cell.backGround.frame=CGRectMake(64, 0, 249, cell
                                             .frame.size.height);
             cell.contentText.frame=CGRectMake(70, 5, 230, size.height);
            height=5.0f;
        }
        
        cell.contentText.numberOfLines=size.height/20;
        cell.contentText.text=[dict  objectForKey:@"str5"];
        /*cell.contentText.hidden=YES;
        cell.eMAsyncImageView.hidden=YES;
        cell.voiceButton.hidden=YES;
        switch ([[dict objectForKey:@"count1"] integerValue]) {
            case 1:{//文本
                cell.contentText.hidden=NO;
                cell.contentText.numberOfLines=size.height/20;
                cell.contentText.text=[dict  objectForKey:@"str5"];
                break;
            }
            case 2:{//图片
                cell.eMAsyncImageView.hidden=NO;
                cell.eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
                cell.eMAsyncImageView.frame=CGRectMake(70,height,100,100);
                cell.eMAsyncImageView.imageId=[dict objectForKey:@"str1"];
                break;
            }
            case 3:{//语音
                cell.voiceButton.hidden=NO;
                cell.voiceButton.frame=CGRectMake(70, height, 38, 38);
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
                cell.voiceButton.tag=indexPath.row;
                [cell.voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
                break;
            }
            case 4:{//视频
                
                break;
            }
        }*/
        
 
      
    }else{
        return nil;
    }
   
    return cell;
}

-(IBAction)onclickSectionAction:(UIButton*)sender{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@""
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"邀请TA", @"回复评论",@"语音回复",nil];
    actionSheet.tag=sender.tag-1;
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"评论数组下标＝%d",actionSheet.tag-HEADERBUTTONTAG);
    if (buttonIndex == 0) {//邀请TA
        [self savePinglinReplyAction:(actionSheet.tag-HEADERBUTTONTAG) andType:0];
    }else if (buttonIndex == 1) {//回复评论
        
        [self savePinglinReplyAction:(actionSheet.tag-HEADERBUTTONTAG) andType:1];
    }else if(buttonIndex == 2) {//语音回复
          
    }else if(buttonIndex == 3) {//取消
         
    }
    
}
-(IBAction)playyuyinAction:(UIButton*)sender{
    if (!self.voiceRecord.hasMp3File) {
        [Utility customAlertWithMsg:@"文件正在生成中,请稍后..." andTitle:@"提醒" andDelagate:nil];
        return;
    }
    
    [self.voiceRecord playMp3BtnClick:@"1"];
}
 
-(IBAction)resetyuyinAction:(UIButton*)sender{
    UIView *playerButton=[self.view viewWithTag:90006];
    [playerButton removeFromSuperview];
    [sender removeFromSuperview];
    UIView *voiceRecordButton=[self.view viewWithTag:90001];
    UILabel *yuyinLabel=(UILabel*)[self.view viewWithTag:90003];
    yuyinLabel.hidden=NO;
    UIButton *leftButton=(UIButton*)[self.view viewWithTag:90005];
    leftButton.hidden=NO;
    voiceRecordButton.userInteractionEnabled=YES;
    voiceRecordButton.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"recordbutton_hover.png"]];
}

-(IBAction)switchButtonAction:(UIButton*)sender{
    UIView *voiceRecordButton=[self.view viewWithTag:90001];
    UIView *dialogbg=[self.view viewWithTag:90002];
    UILabel *yuyinLabel=(UILabel*)[self.view viewWithTag:90003];
    if (!sender.selected) {
        voiceRecordButton.hidden=YES;
        dialogbg.hidden=NO;
        yuyinLabel.hidden=YES;
         [self.dailogField becomeFirstResponder];
    }else{
        yuyinLabel.hidden=NO;
        voiceRecordButton.hidden=NO;
        dialogbg.hidden=YES;
         [self.dailogField resignFirstResponder];
    }
    sender.selected=!sender.selected;

}
-(IBAction)fenxiangAction:(UIButton*)sender{
  // [self.voiceRecord playMp3BtnClick:nil];
}

-(void)longPressBtn:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state]==UIGestureRecognizerStateBegan){//长按事件开始
         UILabel *yuyinLabel=(UILabel*)[self.view viewWithTag:90003];
        yuyinLabel.hidden=YES;
        UIButton *leftButton=(UIButton*)[self.view viewWithTag:90005];
        leftButton.hidden=YES;
        NSLog(@"开始");
        [self.voiceRecord recordBtnClick:@"0"];
       
        
    }else if([gestureRecognizer state]==UIGestureRecognizerStateEnded){//长按事件
        UIImageView *toolsbg=(UIImageView*)[self.view viewWithTag:90000];
        
        UIView *voiceRecordButton=[self.view viewWithTag:90001];
        voiceRecordButton.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"recordfinish_normal.png"]];
        voiceRecordButton.userInteractionEnabled=NO;
        
        [toolsbg addSubview:[Utility customButton:self action:@selector(resetyuyinAction:) normalImage:@"yuyin_back_normal.png" lightedImage:@"yuyin_back_hover.png" frame:CGRectMake(10, 10, 92, 31) title:nil tag:0]];
        UIButton *playerButton=[Utility customButton:self action:@selector(playyuyinAction:) normalImage:@"yuyinplay_normal.png" lightedImage:@"yuyinplay_hover.png" frame:CGRectMake(218, 10, 92, 31) title:nil tag:90006];
        UILabel *labelDuring=[Utility detailTextLabel:CGRectMake(10, 5, 50, 17) andFontSize:12];
        labelDuring.text=self.voiceRecord.duration;
        [playerButton addSubview:labelDuring];
        [toolsbg addSubview:playerButton];
        [self.voiceRecord recordBtnClick:@"0"];
          NSLog(@"结束");
    }
}

#pragma -mark VoiceRecordDelegate
-(void) convertTomp3Success:(NSString*)fileUrl{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSURL *url=[NSURL fileURLWithPath:fileUrl];
    NSData *mp3Data =[NSData  dataWithContentsOfURL:url];
    dispatch_queue_t newThread = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    __weak id selfweak=self;
    dispatch_async(newThread, ^{
        __strong GonggaoViewController *selfstrong=selfweak;
        NSDictionary *result=[selfstrong uploadFile:mp3Data andFile:[NSMutableDictionary dictionaryWithDictionary:@{@"flydyUpload.mp3":mp3Data}]];
        if ([[result objectForKey:@"code"] integerValue]==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [selfstrong.mytableView reloadData];
            });
        }
    });
    
}
/*p.u0	N	评论人ID
 p.p2	N	被评论的对象ID
 p.p3	N	被评论的对象的类型  1圈子//2专题//3博文//4供稿
 p.p4	N	评论内容
 p.t0	N	内容类型  1文本///2图片 ///3语音 //4视频
 */
-(NSDictionary*) uploadFile:(NSData*)imgData andFile:(NSMutableDictionary*)fileparam{
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility getServerUrl],ADDPINGLUN];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    NSString *caogaoId=[self.gonggaoDict objectForKey:@"str1"];
     NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    [param setObject:userId forKey:@"p.u0"];
    [param setObject:caogaoId forKey:@"p.p2"];
    [param setObject:@"4" forKey:@"p.p3"];
    [param setObject:@"" forKey:@"p.p4"];
    for (NSString *key in fileparam.allKeys) {
        if ([key hasSuffix:@"mp3"]) {
            [param setObject:@"3" forKey:@"p.t0"];//语音类型
        }else{
            [param setObject:@"2" forKey:@"p.t0"];//图片类型
        }
        break;
    }

    NSMutableDictionary *result=[[URLRequest alloc] postWithUrl:url fileds:param andFile:fileparam];
    return result;
}


#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.dailogField) {
        if (self.dailogField.text.length>0) {
            [self.dailogField resignFirstResponder];
            [self savePinglinAction];
            return YES;
        }
    }
    return NO;
}
#pragma  -mark  保存评论
-(void) savePinglinAction{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
     NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    [param setObject:userId forKey:@"p.u0"];
    [param setObject:[self.gonggaoDict objectForKey:@"str1"] forKey:@"p.p2"];
    [param setObject:@"4" forKey:@"p.p3"];
    [param setObject:self.dailogField.text forKey:@"p.p4"];
    [param setObject:@"1" forKey:@"p.t0"];
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],ADDPINGLUN];
    
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
      [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}
#pragma  -mark  保存评论回复或邀请他
-(void) savePinglinReplyAction:(int) row andType:(int) type{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSString *pinglunId=[[self.arrayList objectAtIndex:row] objectForKey:@"str7"];
     RelypinglunView *relypinglunView=[[RelypinglunView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    relypinglunView.pinglunId=pinglunId;
    [relypinglunView showInputField:type];
    [app.window addSubview:relypinglunView];
   
}

#pragma mark - Responding to keyboard events

- (void)keyboardWillShow:(NSNotification *)notification {
    UIView *viewField=[self.view viewWithTag:90000];
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = viewField.frame;
    newTextViewFrame.origin.y = keyboardTop-viewField.frame.size.height;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    viewField.frame = newTextViewFrame;
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
     UIView *viewField=[self.view viewWithTag:90000];
    NSDictionary *userInfo = [notification userInfo];
    CGRect newTextViewFrame = viewField.frame;
    newTextViewFrame.origin.y = self.mytableView.frame.size.height;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    viewField.frame = newTextViewFrame;
    [UIView commitAnimations];
}
-(void) initFootLoadingMore{
    UIView *footView=[[UIView alloc] initWithFrame:CGRectMake(0,  0, self.view.frame.size.width, 30)];
    footView.tag=FOOTVIEWTAG;
    footView.backgroundColor=[UIColor  clearColor];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc]
                                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.frame=CGRectMake(100, 5, 20, 20);
    [activityIndicatorView startAnimating];
    
    [footView addSubview:activityIndicatorView];
    UILabel *moreLabel=[[UILabel alloc] initWithFrame:CGRectMake(135, 5, 110, 20)];
    moreLabel.backgroundColor=[UIColor clearColor];
    moreLabel.textColor=[UIColor blackColor];
    moreLabel.font=[UIFont fontWithName:FONT_FAMILY size:12.0f];
    moreLabel.text=LOADING_TITLE_DEFAULT;
    [footView addSubview:moreLabel];
    self.mytableView.tableFooterView=footView;
    self.mytableView.tableFooterView.hidden=YES;
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)playmp3Action:(UIButton*)sender{
    voiceLoading=[[UIView alloc] initWithFrame:sender.frame];
    voiceLoading.backgroundColor=[UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1.0];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.center=CGPointMake((sender.frame.size.width-20)/2, (sender.frame.size.height-30)/2);
    [activityIndicatorView startAnimating];
    [voiceLoading addSubview:activityIndicatorView];
    [sender  addSubview:voiceLoading];
    NSDictionary *dict;
    if ([sender tag]==0) {
        dict=self.gonggaoDict;
    }else{
        dict=[self.arrayList objectAtIndex:[sender tag]-1];
    }
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&type=2",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
    EMAsyncFile *eMAsyncFile=[[EMAsyncFile alloc] init];
    eMAsyncFile.imageIdKey=@"id";
    eMAsyncFile.delegate=self;
    [eMAsyncFile setImageUrl:url];
    
}
#pragma -mark EMAsyncFileDelegate
-(void) fileSuccess:(NSString*)url{
    [voiceLoading removeFromSuperview];
    self.voiceRecord=[[VoiceRecord alloc] init];
    self.voiceRecord.delegate=self;
    [self.voiceRecord playMp3Click:url];
    
}
-(void) fileFail:(NSString*)error{
    [voiceLoading removeFromSuperview];
    
}
@end
